﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows;

namespace SangoDesktop
{
	/// <summary>
	/// Handler the game. This class is designed to code and decode xml messages. It does message handlings in MainWindow's thread.
	/// </summary>
	class GameHandler:System.Windows.Threading.DispatcherObject
	{
		private static GameHandler instance = new GameHandler();
		public static GameHandler GetInstance()
		{
			return instance;
		}

		MessageController messageController;

		/// <summary>
		/// Contrustor.
		/// </summary>
		/// <param name="events">The game events.</param>
		private GameHandler ()
		{
			this.messageController = new MessageController(
				delegate( string Message )
				{
					this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new NewMessage(this.OnReceiveMessage), Message);
				});
		}

		private void OnReceiveMessage ( string message )
		{
			string Message=message as string;
			
		}

		/// <summary>
		/// Defines the returns of the joining.
		/// </summary>
		public enum RegisterReturns { Success, UsedPlayerName, UnKnownError };

		/// <summary>
		/// Join the game.
		/// </summary>
		/// <param name="playerName"></param>
		/// <returns></returns>
		public RegisterReturns Join ( string playerName )
		{
			try
			{
				string r=messageController.Register(playerName);
				XDocument doc = XDocument.Parse(r);
				XElement root = doc.Root;
				if ( root.Attribute("result").Value == "success" )
					return RegisterReturns.Success;
				else
					if ( root.Element("detail").Value == "UsedPlayerName" )
						return RegisterReturns.UsedPlayerName;
					else
						return RegisterReturns.UnKnownError;
			}
			catch
			{
				return RegisterReturns.UnKnownError;
			}			
		}

	}
}
